package com.superbytecode.cloud.rocketmq.configure;

import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.order.OrderProducer;
import com.superbytecode.cloud.rocketmq.consumer.provider.AliMQConsumeProvider;
import com.superbytecode.cloud.rocketmq.producer.provider.AliMQProduceProvider;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: beacon-cloud
 * @Package: com.superbytecode.cloud.rocketmq.configure
 * @ClassName: AliMQConfiguration
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/11/1 16:24
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Configuration
@Import({AliMQProduceProvider.class, AliMQConsumeProvider.class})
@ConditionalOnProperty(name = "rocketmq.server-provider", havingValue = "ali_cloud")
public class AliMQConfiguration {
    @Resource
    private MQConfigurationProperties configurationProperties;

    @Resource
    private RocketMQProperties rocketMqProperties;


    public Properties initAliMqProperties() {
        MQConfigurationProperties.AliMQConfiguration aliMQConfiguration = configurationProperties.getAliMQ();
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.AccessKey, aliMQConfiguration.getAccessKey());
        properties.setProperty(PropertyKeyConst.SecretKey, aliMQConfiguration.getSecretKey());
        properties.setProperty(PropertyKeyConst.NAMESRV_ADDR, rocketMqProperties.getNameServer());
        return properties;
    }


    @Bean
    public Producer producer() {
        Properties properties = initAliMqProperties();
        Producer producer = ONSFactory.createProducer(properties);
        producer.start();
        return producer;
    }

    @Bean
    public OrderProducer orderProducer() {
        Properties properties = initAliMqProperties();
        OrderProducer orderProducer = ONSFactory.createOrderProducer(properties);
        orderProducer.start();
        return orderProducer;
    }

}